package org.sacgtug.location.service;

import java.io.StringWriter;
import java.util.Collections;
import java.util.Iterator;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;


@Path("/location/")
public class LocationArtifacts {
	
	private static Cache locationCache;
	
	static {
		try {
			locationCache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
			locationCache.put("locationIds", 0);
			locationCache.put("artifactIds", 0);
			locationCache.put("keys", "");
		}
		catch (CacheException e) {
			
		}
	}
	
	@GET
	@Path("{locationId}")
	@Produces("application/json")
	public String getLocation(@PathParam("locationId") int locationId) {
		
		return (String) locationCache.get(locationId);
		
	}
	
	@GET
	@Path("/all/")
	@Produces("application/json")
	public String getAllLocations() {
		
		StringBuffer response = new StringBuffer();
		
		String keys = (String) locationCache.get("keys");
		String[] items = keys.split(":");
		for(String item : items) {
			if(null != item && item.length() != 0) {
				response.append(toJson(locationCache.get(Integer.parseInt(item)), true));
			}
		}

		return response.toString();		
	}
	
	@PUT
	@Path("{latitude}/{longitude}/{message}")
	@Produces("application/json")
	public Location createLocation(@PathParam("latitude") double latitude,
								   @PathParam("longitude") double longitude,
								   @PathParam("message") String message) {
		
		int locationIds = (Integer) locationCache.get("locationIds");
		int artifactIds = (Integer) locationCache.get("artifactIds");
		
		Artifact artifact = new Artifact(artifactIds++, message);
		Location location = new Location(locationIds++, latitude, longitude, artifact);
		
		String keys = (String) locationCache.get("keys");
		
		keys += Integer.toString(location.getId()) + ":";
		locationCache.put("keys", keys);
		locationCache.put(location.getId(), toJson(location, true));
		
		locationCache.put("locationIds", locationIds);
		locationCache.put("artifactIds", artifactIds);
		
		return location;
	}
	
	protected String toJson(Object o, boolean pretty) {
		ObjectMapper mapper = new ObjectMapper();
		
		if (pretty)
		{
			mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); 
		}

		StringWriter w = new StringWriter();
		try {
			mapper.writeValue(w, o);
		} catch (Exception e) {
			//
		}
		
		return w.toString();
	}
}
